package com.mai4j.maiadmin.setup.gen.jooq;

import com.mai4j.maiadmin.setup.Env;
import lombok.extern.slf4j.Slf4j;
import org.jooq.codegen.DefaultGeneratorStrategy;
import org.jooq.meta.CatalogDefinition;
import org.jooq.meta.Definition;
import org.jooq.meta.SchemaDefinition;
import org.jooq.tools.StringUtils;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Slf4j
public class SkipPrefixGeneratorStrategy extends DefaultGeneratorStrategy {

    @Override
    public String getJavaClassName(Definition definition, Mode mode) {
        String name = getFixedJavaClassName(definition);
        if (name != null)
            return name;
        else
            return getJavaClassName0(definition.getOutputName(), mode);
    }

    /**
     * 过滤掉表前缀
     *
     * @param definition definition
     * @return JavaIdentifier
     */
    @Override
    public String getJavaIdentifier(Definition definition) {
        String jId = super.getJavaIdentifier(definition);
        Env.Db db = Env.db();
        String prefix = db.getPrefix();
        if (!StringUtils.isBlank(prefix) && jId.startsWith(prefix.toUpperCase())) jId = jId.substring(prefix.length());
        return jId;
    }

    private String getJavaClassName0(String outputName, Mode mode) {
        Env.Db db = Env.db();
        String prefix = db.getPrefix();
        if (!StringUtils.isBlank(prefix) && outputName.startsWith(prefix)) {
            outputName = outputName.substring(prefix.length());
        }
        StringBuilder result = new StringBuilder();
        result.append(StringUtils.toCamelCase(
                outputName.replace(' ', '_')
                        .replace('-', '_')
                        .replace('.', '_')
        ));
        if (mode == Mode.RECORD)
            result.append("Record");
        else if (mode == Mode.DAO)
            result.append("Dao");
        else if (mode == Mode.INTERFACE)
            result.insert(0, "I");
        return result.toString();
    }

    /**
     * [#4168] [#5783] Some class names must not be modified by custom strategies.
     */
    final String getFixedJavaClassName(Definition definition) {
        // [#2032] Intercept default catalog
        if (definition instanceof CatalogDefinition && ((CatalogDefinition) definition).isDefaultCatalog())
            return "DefaultCatalog";
            // [#2089] Intercept default schema
        else if (definition instanceof SchemaDefinition && ((SchemaDefinition) definition).isDefaultSchema())
            return "DefaultSchema";

        else
            return null;
    }
}
